package com.carl.guli.api.filter;

import com.alibaba.fastjson.JSONObject;
import com.carl.guli.common.util.DateUtil;
import com.carl.guli.common.util.HttpUtil;
import com.carl.guli.common.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by youzm on 2017/5/17.
 */
public class ApiFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(ApiFilter.class);



    private FilterConfig configHost;

    private String key = "OW]kzv!SLTpaiThvpQ";

    private String[] configHosts = null;

    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        logger.debug("[ApiFilter] 当前请求URL={}",request.getRequestURI());
        //微信验证
        //token校验
        if(validateToken(request)){
            System.out.println("youzmtest-----当前请求正常");
            chain.doFilter(request, response);
        }

//        System.out.println("youzmtest-----当前请不不不不不不不");
//        chain.doFilter(req, resp);
        return;
    }

    private boolean validateToken(HttpServletRequest request) {
        String header = request.getHeader("user-agent");//Mozilla/5.0 (iPhone; CPU iPhone OS 9_2_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13D15 MicroMessenger/6.3.13 NetType/WIFI Language/zh_CN

//        if (!HttpUtil.isRequestFromWexin(header)){
//            return false;
//        }
//
//        String acceptToken = request.getHeader("accepttoken");
//
//        String md5String = MD5Util.getMD5String(key);
//        if (!md5String.endsWith(acceptToken)){
//            return false;
//        }
//

        return true;
    }

    private boolean isExclude(String tempContextUrl) {
        if (null == configHosts) {
            return true;
        } else {
            for (String excludeUrl : configHosts) {
                if (tempContextUrl.indexOf(excludeUrl) >= 0) {
                    return true;
                }
            }
        }
        return false;
    }

    public void init(FilterConfig config) throws ServletException {
    }

}
